package com.platform.hjt.base.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.platform.hjt.base.costant.SessionConstant;


public class LoginInterceptor extends HandlerInterceptorAdapter{
	private static final String LOGIN_URL = "/login/login.html";

	@Override  
	public boolean preHandle(HttpServletRequest request,  
			HttpServletResponse response, Object handler) throws Exception {  
		
		if(request.getSession().getAttribute(SessionConstant.SESSION_USER) == null){
			request.getSession().setAttribute("url", request.getServletPath().replace("/", ""));
			if(request.getHeader("x-requested-with") != null
					&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){

				response.setContentType("application/json;charset=UTF-8");
				PrintWriter out = response.getWriter();
				JSONObject result = new JSONObject();
				
				result.put("result", false);
				result.put("msg", "请先登入后在操作");
				result.put("url", request.getContextPath() + LOGIN_URL );
				
				out.print(result);
				out.flush();
				out.close();
			}else{
				PrintWriter pw = response.getWriter();
				pw.write("<script>top.window.location.href = '"+ request.getContextPath() + LOGIN_URL+"?r='+Math.random() ;</script>");
				pw.flush();
				pw.close();
				//response.sendRedirect( request.getContextPath() + LOGIN_URL);
			}
			return false;
		}

		return super.preHandle(request, response, handler);  
	}

	@Override  
	public void postHandle(HttpServletRequest request,  
			HttpServletResponse response, Object handler,  
			ModelAndView modelAndView) throws Exception {  
	}  

	@Override  
	public void afterCompletion(HttpServletRequest request,  
			HttpServletResponse response, Object handler, Exception ex)  
					throws Exception {  
	} 
}
